package com.chianghao.qyt.controller.manage_api;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chianghao.qyt.controller.manage_api.dto.*;
import com.chianghao.qyt.controller.manage_api.vo.MenuVo;
import com.chianghao.qyt.controller.manage_api.vo.LoginUserInfoVo;
import com.chianghao.qyt.controller.manage_api.vo.SysOperationAdminVo;
import com.chianghao.qyt.controller.manage_api.vo.TokenInfoVo;
import com.chianghao.qyt.entity.SysOperationAdmin;
import com.chianghao.qyt.entity.SysOperationMenu;
import com.chianghao.qyt.entity.SysOperationRole;
import com.chianghao.qyt.service.SysOperationAdminService;
import com.chianghao.qyt.service.SysOperationMenuService;
import com.chianghao.frame.core.auth.AuthRequestContext;
import com.chianghao.frame.core.auth.whilte_list.AuthenticationWhitelist;
import com.chianghao.frame.core.model.Page;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("manage/api/operation-admin")
public class SysOperationAdminController {

    @Resource
    SysOperationAdminService sysOperationAdminService;

    @Resource
    SysOperationMenuService sysOperationMenuService;


    @PostMapping("login")
    @AuthenticationWhitelist
    public TokenInfoVo login(HttpServletRequest request, @RequestBody TokenInfoDto dto){
        HttpSession  session = request.getSession(false);
        if(session!=null){
            session.invalidate();
        }

        String newSessionId = request.getSession(true).getId();
        String token = sysOperationAdminService.login(newSessionId,dto.getAccount(),dto.getPassword());
        TokenInfoVo vo = new TokenInfoVo();
        vo.setToken(token);
        return vo;
    }

    @PostMapping("modify-self-password")
    public Boolean modifyPassword(@RequestBody ModifyLoginUserPasswrodDto dto){
        Long userId = Long.parseLong(AuthRequestContext.getUserId());
        this.sysOperationAdminService.modifyPassword(userId,dto.getOldPassword(),dto.getNewPassword(),dto.getNewPasswordConfirm());
        return true;
    }


    @GetMapping("logout")
    public Boolean logout(HttpServletRequest request){
        Long userId = Long.parseLong(AuthRequestContext.getUserId());
        sysOperationAdminService.logout(userId);
        return true;
    }

    @PostMapping("role/setting")
    public Boolean setSysOperationRole(@RequestBody SetSysOperationRoleDto dto){
        sysOperationAdminService.setSysOperationRole(dto.getAccountId(),new HashSet<Long>(){{add(dto.getRoleId());}});
        return true;
    }




    @GetMapping("account")
    public LoginUserInfoVo getOperationAccount(){
        Long userId = Long.parseLong(AuthRequestContext.getUserId());
        SysOperationAdmin admin = this.sysOperationAdminService.queryById(userId);
        LoginUserInfoVo vo  = new LoginUserInfoVo();
        vo.setIcon(admin.getIcon()==null?"imgs/user.png":admin.getIcon());
        vo.setUserName(admin.getUserName());
        return vo;
    }

    @GetMapping("page")
    public Page<SysOperationAdminVo> accountPageList(@RequestParam("pageIndex") int pageIndex, @RequestParam("pageSize") int pageSize){
        Long userId = Long.parseLong(AuthRequestContext.getUserId());
        IPage<SysOperationAdmin> pages =this.sysOperationAdminService.queryPage(userId,pageIndex,pageSize);
        Page<SysOperationAdminVo> result = new Page<>();

        Map<Long,List<SysOperationRole>> accountRoleMap  = sysOperationAdminService.selectAccountRoleMap(pages.getRecords().stream().map(SysOperationAdmin::getId).collect(Collectors.toSet()));

        result.setTotal(pages.getTotal());
        result.setItems(pages.getRecords().stream().map(i->{
            SysOperationAdminVo item = new SysOperationAdminVo();
            item.setId(i.getId());
            item.setAccount(i.getAccount());
            item.setName(i.getUserName());
            List<SysOperationRole> roles = accountRoleMap ==null?null:accountRoleMap.get(i.getId());
            if(roles!=null&& !roles.isEmpty()){
                item.setRoles(roles);
                StringBuilder sb = new StringBuilder();
                int index = 0;
                for(SysOperationRole r:roles){
                    if(index!=0){
                        sb.append(",");
                    }
                    sb.append(r.getRoleName());
                    index++;
                }
                item.setRoleNames(sb.toString());
            }
            return item;
        }).toList());
        return result;
    }




    /**
     * 添加人员账号
     * @param dto 参数
     * @return 成功
     */
    @PostMapping("add")
    public Boolean addOperationAdmin(@RequestBody OperationAdminAddDto dto){
        this.sysOperationAdminService.addAdmin(dto.getAccount(),dto.getUsername(),dto.getPassword());
        return true;
    }

    /**
     * 修改账号信息
     * @param dto 参数
     * @return 成功
     */
    @PostMapping("modify")
    public Boolean modifyOperationAdmin(@RequestBody OperationAdminModifyDto dto){
        this.sysOperationAdminService.modifyAdmin(dto.getId(),dto.getAccount(),dto.getUsername());
        return true;
    }


    /**
     * 修改人员密码
     * @param dto 参数
     * @return 成功
     */
    @PostMapping("password/modify")
    public Boolean modifyAdminPassword(@RequestBody OperationAdminPasswordModifyDto dto){
        this.sysOperationAdminService.modifyAdminPassword(dto.getId(),dto.getPassword());
        return true;
    }

    /**
     * 删除账号
     * @param id 参数
     * @return 成功
     */
    @DeleteMapping("{id}")
    public Boolean deleteOperationAdmin(@PathVariable("id") Long id){
        this.sysOperationAdminService.delete(id);
        return true;
    }

}
